<script setup>
import { useCartStore } from '@/stores/cartStore';
import { useUserStore } from '@/stores/userStore';
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';

const cartStore = useCartStore();
const userStore = useUserStore();
const router = useRouter();

console.log('购物车页面初始化');

// 更准确地检查登录状态
const checkLoginStatus = () => {
  // 根据返回的数据结构，token存储在userInfo.data.token中
  console.log('用户信息:', userStore.userInfo);
  const token = userStore.userInfo?.data?.token;
  console.log('检查token:', token);
  return !!token;
};

// 单选回调
const singleCheck = (i, selected) => {
    console.log('单选商品:', { item: i, selected });
    cartStore.singleCheck(i.skuId, selected);
};

const allCheck = (selected) => {
    console.log('全选操作:', selected);
    cartStore.allCheck(selected);
};

// 删除选中商品
const batchDelCart = () => {
    console.log('执行批量删除');
    const selectedIds = cartStore.selectedSkuIds;
    console.log('选中的商品ID:', selectedIds);
    if (selectedIds.length > 0) {
        cartStore.batchDelCart(selectedIds);
    } else {
        console.log('没有选中的商品');
    }
};

// 处理商品数量变化
const handleCountChange = (item, value) => {
    console.log('商品数量变化:', { item, value });
    // 确保传入的数量是有效的正整数
    const validValue = Math.max(1, parseInt(value) || 1);
    if (validValue > 0) {
        // 直接更新本地值，确保界面立即响应
        const oldCount = item.count;
        item.count = validValue;
        // 调用store方法更新数据库中的数量
        cartStore.updateCartCount(item.skuId, validValue).catch((error) => {
            // 如果更新失败，恢复原来的值
            console.error('更新商品数量失败:', error);
            item.count = oldCount;
        });
    }
};

// 跳转到结算页面
const goToCheckout = () => {
  console.log('跳转到结算页面');
  // 检查是否有选中的商品
  const selectedItems = cartStore.cartList.filter(item => item.selected);
  if (selectedItems.length === 0) {
    console.log('没有选中任何商品');
    return;
  }
  
  // 跳转到结算页面
  router.push('/checkout');
};

// 组件挂载时获取购物车列表
onMounted(async () => {
    console.log('购物车页面挂载完成');
    const isLogin = checkLoginStatus();
    console.log('当前登录状态:', isLogin);
    // 注意：合并购物车操作已经在用户登录时完成，这里只需要更新购物车列表
    console.log('更新购物车列表');
    await cartStore.updateNewList();
});
</script>

<template>
    <div class="xtx-cart-page">
        <div class="container m-top-20">
            <div class="cart">
                <table>
                    <thead>
                        <tr>
                            <th width="120">
                                <el-checkbox :model-value="cartStore.isAll" @change="allCheck" />
                            </th>
                            <th width="400">商品信息</th>
                            <th width="220">单价</th>
                            <th width="180">数量</th>
                            <th width="180">小计</th>
                            <th width="140">操作</th>
                        </tr>
                    </thead>
                    <!-- 商品列表 -->
                    <tbody>
                        <tr v-for="i in cartStore.cartList" :key="i.id">
                            <td>
                                <!-- 单选框 -->
                                <el-checkbox :model-value="i.selected"
                                    @change="(selected) => singleCheck(i, selected)" />
                            </td>
                            <td>
                                <div class="goods">
                                    <RouterLink to="/"><img :src="i.picture" alt="" /></RouterLink>
                                    <div>
                                        <p class="name ellipsis">
                                            {{ i.name }}
                                        </p>
                                    </div>
                                </div>
                            </td>
                            <td class="tc">
                                <p>&yen;{{ i.price }}</p>
                            </td>
                            <td class="tc">
                                <el-input-number 
                                  v-model="i.count" 
                                  :min="1"
                                  @change="(value) => handleCountChange(i, value)" />
                            </td>
                            <td class="tc">
                                <p class="f16 red">&yen;{{ (i.price * i.count).toFixed(2) }}</p>
                            </td>
                            <td class="tc">
                                <p>
                                    <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消"
                                        @confirm="cartStore.delCart(i.skuId)">
                                        <template #reference>
                                            <a href="javascript:;">删除</a>
                                        </template>
                                    </el-popconfirm>
                                </p>
                            </td>
                        </tr>
                        <tr v-if="cartStore.cartList.length === 0">
                            <td colspan="6">
                                <div class="cart-none">
                                    <el-empty description="购物车列表为空">
                                        <el-button type="primary">随便逛逛</el-button>
                                    </el-empty>
                                </div>
                            </td>
                        </tr>
                    </tbody>

                </table>
            </div>
            <!-- 操作栏 -->
            <div class="action">
                <div class="batch">
                    共 {{ cartStore.allCount }} 件商品，已选择 {{ cartStore.selectedCount }} 件，商品合计：
                    <span class="red">¥ {{ cartStore.selectedPrice.toFixed(2) }} </span>
                    <el-popconfirm 
                      title="确认删除选中的商品吗?" 
                      confirm-button-text="确认" 
                      cancel-button-text="取消"
                      @confirm="batchDelCart">
                        <template #reference>
                            <a href="javascript:;" v-if="cartStore.selectedCount > 0">批量删除</a>
                        </template>
                    </el-popconfirm>
                </div>
                <div class="total">
                    <el-button size="large" type="primary" @click="goToCheckout" :disabled="cartStore.selectedCount === 0">下单结算</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped lang="scss">
.xtx-cart-page {
    margin-top: 20px;

    .cart {
        background: #fff;
        color: #666;

        table {
            border-spacing: 0;
            border-collapse: collapse;
            line-height: 24px;

            th,
            td {
                padding: 10px;
                border-bottom: 1px solid #f5f5f5;

                &:first-child {
                    text-align: left;
                    padding-left: 30px;
                    color: #999;
                }
            }

            th {
                font-size: 16px;
                font-weight: normal;
                line-height: 50px;
            }
        }
    }

    .cart-none {
        text-align: center;
        padding: 120px 0;
        background: #fff;

        p {
            color: #999;
            padding: 20px 0;
        }
    }

    .tc {
        text-align: center;

        a {
            color: $xtxColor;
        }

        .xtx-numbox {
            margin: 0 auto;
            width: 120px;
        }
    }

    .red {
        color: $priceColor;
    }

    .green {
        color: $xtxColor;
    }

    .f16 {
        font-size: 16px;
    }

    .goods {
        display: flex;
        align-items: center;

        img {
            width: 100px;
            height: 100px;
        }

        >div {
            width: 280px;
            font-size: 16px;
            padding-left: 10px;

            .attr {
                font-size: 14px;
                color: #999;
            }
        }
    }

    .action {
        display: flex;
        background: #fff;
        margin-top: 20px;
        height: 80px;
        align-items: center;
        font-size: 16px;
        justify-content: space-between;
        padding: 0 30px;

        .xtx-checkbox {
            color: #999;
        }

        .batch {
            a {
                margin-left: 20px;
            }
        }

        .red {
            font-size: 18px;
            margin-right: 20px;
            font-weight: bold;
        }
    }

    .tit {
        color: #666;
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
    }

}
</style>